package dyl.easycode.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.lingala.zip4j.io.ZipOutputStream;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import dyl.common.exception.CommonException;
import dyl.common.util.JdbcTemplateUtil;
import dyl.common.util.Page;
import dyl.easycode.bean.EasyCode;
import dyl.easycode.bean.Table;
import dyl.easycode.service.EasyCodeServiceImpl;
import dyl.easycode.util.FreemarkerUtils;
import dyl.sys.action.BaseAction;
import freemarker.template.Configuration;
/**
 * 由dyl EasyCode自动生成
 * @author Dyl
 * 2017-05-31 15:06:00
 */
@Controller
public class EasyCodeAction extends BaseAction{
	@Resource
	private JdbcTemplateUtil jdbcTemplate;
	@Resource
	private EasyCodeServiceImpl easyCodeServiceImpl;
	
	 /**
	 * 说明：进入主页面方法
	 * @return String
	 */
	@RequestMapping(value = "/easyCode!main.do")
	public String main(Page page,EasyCode easyCode,HttpServletRequest request){
		try{
			request.setAttribute("easyCodeList",easyCodeServiceImpl.findEasyCodeList(page, easyCode));
			request.setAttribute("easyCode", easyCode);
		} catch (Exception e) {
			throw new CommonException(request, e);
		}
		return "/sys/easyCode/easyCodeMain";
	}
	@RequestMapping(value = "/easyCode!easyCodeForm.do")
	public String easyCodeForm(Page page,EasyCode easyCode,HttpServletRequest request){
		try{
			request.setAttribute("table", new Table(easyCode.getName()));
		} catch (Exception e) {
			throw new CommonException(request, e);
		}
		return "/sys/easyCode/easyCodeForm";
	}
	/**
	 * 生成代码
	 * @param request
	 * @param response
	 * @param easyCode
	 * @throws Exception
	 */
	@RequestMapping(value = "/easyCode.do")
   	public void easyCode(HttpServletRequest request,HttpServletResponse response,EasyCode easyCode) throws Exception {
	 	
    	String destPath=getClass().getResource("").getFile().toString();
    	String templatePath=getClass().getResource("../template/layui").getFile().toString();
		//组装ftl需要的参数
    	HashMap<String, Object> root = new HashMap<String, Object>();
		root.put("table", easyCodeServiceImpl.getColumnList(easyCode));
		root.put("sysTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		//是否包含上传
		//root.put("hasUpload","true");
		root.put("hasEdit",easyCode.getHasEdit());
		root.put("hasDelete",easyCode.getHasDelete());
		root.put("hasAuth",easyCode.getHasAuth());
		Configuration cfg = FreemarkerUtils.getConfiguration(templatePath);
		for (int i = 0; i < easyCode.getTemplates().length; i++) {
			String arr[] = easyCode.getTemplates()[i].split("@");
			FreemarkerUtils.createFile(cfg,arr[0],root,destPath+arr[1]);
		}
		downloadZip(request, response,easyCode.getTemplates(),destPath);
   	}
    private void downloadZip(HttpServletRequest request,HttpServletResponse response,String[] templates,String destPath) throws Exception{
    	//设置文件ContentType类型
		response.setContentType("application/zip");
		//设置附加文件名
		String zipName ="代码.zip";
		setFileDownloadHeader(request, response, zipName);
    	ZipOutputStream outputStream = new ZipOutputStream(response.getOutputStream());
    	ZipParameters parameters = new ZipParameters();  
    	parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);  
    	parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); 
    	for (String str : templates) {
    	    File file = new File(destPath+str.split("@")[1]);
    	    parameters.setFileNameInZip(file.getName());
    	    parameters.setSourceExternalStream(true);
    	    outputStream.putNextEntry(file,parameters);  
    	    if (file.isDirectory()){
    	        outputStream.closeEntry();  
    	        continue;  
    	    }  
    	    InputStream  inputStream = new FileInputStream(file);  
    	    byte[] readBuff = new byte[4096];  
    	    int readLen = -1;  
    	    while ((readLen = inputStream.read(readBuff)) != -1) {  
    	        outputStream.write(readBuff, 0, readLen);  
    	    }  
    	      
    	    outputStream.closeEntry();  
    	      
    	    inputStream.close();  
    	    
    	    //删除文件
    	    file.delete();
    	}  
    	  
    	outputStream.finish();  
    	  
    	outputStream.close();  
      }
	    /**
		 * 设置让浏览器弹出下载对话框的Header.
		 * 根据浏览器的不同设置不同的编码格式  防止中文乱码
		 * @param fileName 下载后的文件名.
		 */
		public static void setFileDownloadHeader(HttpServletRequest request,HttpServletResponse response, String fileName) {
		    try {
		        //中文文件名支持
		        String encodedfileName = null;
		        String agent = request.getHeader("USER-AGENT");
		        //IE11 使用 Gecko, 不大于10使用 MSIE
				if(null != agent && (-1 != agent.indexOf("MSIE") || -1 != agent.indexOf("like Gecko"))){//IE
		            encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8");
		        }else if(null != agent && -1 != agent.indexOf("Mozilla")){
		            encodedfileName = new String (fileName.getBytes("UTF-8"),"iso-8859-1");
		        }else{
		            encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8");
		        }
		        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
		    } catch (UnsupportedEncodingException e) {
		        e.printStackTrace();
		    }
		}
}
